package com.fastbee.web.wnx.service;

import com.alibaba.fastjson.JSONArray;
import com.fastbee.common.utils.uuid.IdUtils;
import com.fastbee.web.wnx.GetWnxApiData;
import com.fastbee.web.wnx.entity.Customer;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class CustomerService {
    private static final Logger log = LoggerFactory.getLogger(CustomerService.class);
    @Autowired
    private DatabaseMetaService databaseMetaService;
    /**
     * 设备运行统计
     */
    public void loadCustomer() {
        Integer apiCode=159;
        long timestamp = System.currentTimeMillis() / 1000;
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("queryid", apiCode.toString());
        String token = GetWnxApiData.generateToken(timestamp,paraMap);
        String jsonInputString =  String.format("{\"timestamp\":%d,\"token\":\"%s\"}" ,timestamp, token);
        System.out.println("发送数据:"+jsonInputString);
        List<Customer> list = new ArrayList<>();
        getWnxApiData(apiCode,jsonInputString,list);
        if(databaseMetaService.testDataSourceConnection("secondary")){
           // Map<String, Object> conditions = new HashMap<>();
            //conditions.put("date_at",dateAt);
            databaseMetaService.batchDeleteByAll("secondary","szh_customer");
            for(Customer customer:list){
                String insertSql = Customer.insertSql();
                Long secondary = databaseMetaService.insertAndReturnKey("secondary", insertSql,
                        IdUtils.simpleUUID(), customer.getCode(),
                        customer.getName(),
                        customer.getAlias(),customer.getState(),
                        customer.getSource(),customer.getCategory(),
                        customer.getAddress(),customer.getProvince(),
                        customer.getCity(),customer.getCounty());
                if(secondary==null){
                    log.error("新增失败");
                }
            }
        }
    }

    public Boolean getWnxApiData(Integer apiCode, String jsonData, List<Customer> list)  {
        try {
            String response = GetWnxApiData.sendPostRequestFixed("/api/squeryc/" + apiCode, jsonData);
            if(response.startsWith("{\"Code\":")){
                return false;
            }else if(response.equals("[]")){
                return false;
            }else{
                list.addAll(JSONArray.parseArray(response, Customer.class));
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
